package com.itcoon.cloud.framework.transform.register;

import com.itcoon.cloud.framework.transform.definition.ModelDefinition;
import com.itcoon.cloud.framework.transform.definition.ModelPropertyDefinition;
import com.itcoon.cloud.framework.transform.pool.AssembleBeanHolder;
import com.itcoon.cloud.framework.transform.utils.TransformServiceUtils;
import com.itcoon.cloud.framework.utils.MethodUtil;
import org.springframework.util.ReflectionUtils;

import java.util.List;

public class ModelDefinitionRegister {

    public <T, R> void register(Class<R> targetType,  Class<T> sourceType) {
        ModelDefinition md = new ModelDefinition();
        md.setTargetClass(targetType);
        md.setOriginClass(sourceType);
        List<TransformServiceUtils.Descriptor> descriptors = TransformServiceUtils.getDescriptors(targetType);
        for (TransformServiceUtils.Descriptor descriptor : descriptors) {
            ModelPropertyDefinition mpd = new ModelPropertyDefinition(md);
            mpd.setAnnotated(descriptor.getAnnotation() != null);
            mpd.setTargetGetter(descriptor.getGetter());
            mpd.setTargetSetter(descriptor.getSetter());
            mpd.setTargetField(descriptor.getField());
            mpd.setTargetAttribute(descriptor.getAttribute());
            mpd.setOriginField(ReflectionUtils.findField(sourceType, descriptor.getOriginAttribute()));
            mpd.setOriginAttribute(descriptor.getOriginAttribute());
            try {
                mpd.setOriginGetter(sourceType.getMethod(MethodUtil.formatGetterName(descriptor.getOriginAttribute())));
            } catch (NoSuchMethodException e) {}
            md.getPropertyDefinitions().add(mpd);
        }
        AssembleBeanHolder.getInstance().registerModelDefinition(md);
    }
}
